import React, { Component } from 'react'

export default class Fetch extends Component {
    constructor() {
        super();
        this.state = {
            list: []
        }
    }
    getData() {
        fetch('http://localhost:3000/play/category')
            .then(res => res.json())
            .then(res => {
                console.log(111, res);
            })
    }
    postData() {
        fetch('http://localhost:3000/users/register', {
            // post 请求
            method: 'POST',
            // 数据
            body: JSON.stringify({
                phone: '18937366671',
                code: 'r2b7',
                password: '123456',
                username: 'Tom'
            })
        })
            .then(res => res.json())
            .then(res => {
                console.log(222, res);
            })
    }
    getData1() {
        this.http('/play/category')
            .then(res => {
                // console.log(res);
                this.setState({
                    list: res
                })
            })
    }
    postData1() {
        this.http.post('http://localhost:3000/users/register',
            {
                phone: '18937366671',
                code: 'r2b7',
                password: '123456',
                username: 'Tom'
            })
            .then(data => {
                console.log(data);
            })

    }
    componentDidMount() {
        // 在这个钩子函数中发请求获取页面中的数据
        this.getData1()
    }
    render() {
        return (
            <div>
                <button onClick={() => this.getData()}>fetch-get</button>
                <button onClick={() => this.postData()}>fetch-post</button>
                <p>=======================================</p>
                <button onClick={() => this.getData1()}>axios-get</button>
                <button onClick={() => this.postData1()}>axios-post</button>
                <p>=======================================</p>
                <ul>
                {
                    this.state.list.map((item, index) => {
                        return (
                            <li key={index}>{item.title}</li>
                        )
                    })
                }
                </ul>
            </div>
        )
    }
}
